#include "filetransf.h"

int send(char* filename,FILE* stream){
	int fichier;
	unsigned char d;
	unsigned int c = 0;
	unsigned int block = 0;
	unsigned int maskBlock = (1<<(LOG2_BLOCKSIZE))-1;
	unsigned int blockSize = (1<<LOG2_BLOCKSIZE);
	
	fichier = open(filename,O_RDONLY);
	if(fichier == -1){
		fprintf(stderr,"Could not open the file\n");
		return 0;
	}

	for(c = 0;; c = (c+1)&(maskBlock) ){

		if(!read(fichier,&d,(size_t)1))
			break;
		if(c == 0)
			fprintf(stream,"%08X",block);
		fprintf(stream,"%02X",d);
	
		if(c == blockSize-1){
			fprintf(stream,"\n");
			block++;
		}
	}
	if(c != 0){
		for(;c< blockSize;c++){
			fprintf(stream,"OO");
		}
		fprintf(stream,"\n");
	}
	fprintf(stream,"%08X",-1);
	close(fichier);
	fprintf(stream,"\n");
	return 0;
}


int receive(char* filename,FILE* stream){
	int fichier;	
	unsigned int blockn;
	int byten;
	unsigned int i;
	char hex[3];

	int blocksize = 1<<LOG2_BLOCKSIZE;
	unsigned char buff[16];
	unsigned char d;
	int resp;

	hex[2] = '\0';
     	fichier = open(filename,O_RDWR | O_CREAT, 
			S_IRUSR |
			S_IWUSR |
			S_IRGRP |
			S_IROTH);
	if(fichier == -1){
		perror("filetransf");
		exit(0);
	}
	while(fscanf(stream,"%08X",&blockn) && blockn != -1){
		for(byten = 0;byten<blocksize;byten++){
			fscanf(stream,"%c%c",hex,hex+1);
			if(hex[0] == 'O'){
				break;
			}
			sscanf(hex,"%02X",&i);
			d = i;
			buff[byten] = d;
		}
		resp = write(fichier,buff,byten);
		if(resp != byten){
			fprintf(stderr,"Could not write to file\n");
			perror("filetransf");
			return 0;
		}
	}
	close(fichier);
	return 0;
}

